Meteor.loginWithWechat = function(options, callback) {
    // support a callback without options
    if (!callback && typeof options === "function") {
        callback = options;
        options = null;
    }
    Wechat.requestCredential(options, callback);
};

Wechat = {};

Wechat.requestCredential = function(options, credentialRequestCompleteCallback) {
    if (!credentialRequestCompleteCallback && typeof options === 'function') {
        credentialRequestCompleteCallback = options;
        options = {};
    }
    var config = ServiceConfiguration.configurations.findOne({
        service: 'wechat'
    });
    if (!config) {
        credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError());
        return;
    }
    var scope = (options && options.requestPermissions) || 'snsapi_userinfo';
    var state = (options && options.loginUrlParameters) || '';
    var redirectUrl = (options && options.redirectUrl) || __meteor_runtime_config__.ROOT_URL + '/wechat/oauth';
    var loginUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize' + 
    '?appid=' + config.appId + 
    '&redirect_uri=' + redirectUrl + 
    '&response_type=code' + 
    '&scope=' + scope + 
    '&state=' + state + 
    '#wechat_redirect';
    window.location = loginUrl;
};